import json
from openai import OpenAI

from config.model_config import get_base_open_ai, xin_qwen_model


# 1. 定义工具函数（开发者本地实现）
def get_weather(city: str):
    """模拟天气API返回数据"""
    weather_data = {
        "上海": {"temp": 25, "condition": "多云"},
        "北京": {"temp": 30, "condition": "晴"}
    }
    return weather_data.get(city, {"error": "城市不存在"})


# 2. 用户提问触发工具调用
client = get_base_open_ai()
messages = [{'role': 'system', 'content': "你是一个有用的帮手，可以使用合适的工具解决我的我问题"}, {'role': 'user', 'content': "上海现在天气怎么样"}]
response = client.chat.completions.create(
    model=xin_qwen_model,
    messages=messages,
    tools=[{
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "获取指定城市的天气信息",
            "parameters": {
                "type": "object",
                "properties": {"city": {"type": "string"}},
                "required": ["city"]
            }
        }
    }]
)
print(response.choices[0])
# 3. 解析工具调用请求
if response.choices[0].message.tool_calls:
    tool_call = response.choices[0].message.tool_calls[0]
    if tool_call.function.name == "get_weather":
        args = json.loads(tool_call.function.arguments)
        weather_result = get_weather(args["city"])  # 执行本地函数

        messages.append({"role": "assistant", "content": None, "tool_calls": [tool_call]})
        messages.append( {"role": "tool", "content": json.dumps(weather_result), "tool_call_id": tool_call.id})
        print("message = ", messages)
        # 4. 将结果返回给模型生成最终响应
        final_response = client.chat.completions.create(
            model="Qwen2.5-0.5B-Instruct",
            messages=messages
        )
        print(final_response.choices[0].message.content)
        # 输出示例：上海当前多云，气温25°C
